package com.heima.user.controller.v1;


import com.heima.model.common.dtos.ResponseResult;
import com.heima.model.common.enums.AppHttpCodeEnum;
import com.heima.model.user.dtos.LoginDto;
import com.heima.model.user.pojos.ApUser;
import com.heima.user.service.ApUserService;
import com.heima.user.service.SendSmsService;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import org.apache.commons.lang.RandomStringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.data.redis.core.StringRedisTemplate;
import org.springframework.web.bind.annotation.*;

import java.util.concurrent.TimeUnit;

@RestController
@RequestMapping("/api/v1/login")
@Api(tags = "用户登录")
public class ApUserLoginController {

    @Autowired
    private ApUserService apUserService;

    @PostMapping("/login_auth")
    @ApiOperation("app端用户登录")
    public ResponseResult login(@RequestBody LoginDto dto){
        //int a = 1/0;//不可控

        //可控
        /*if(true){
            throw new CustomException(AppHttpCodeEnum.NEED_ADMIND);
        }*/
        return apUserService.login(dto);
    }

    @Autowired
    private SendSmsService sendSmsService;

    @Autowired
    private StringRedisTemplate redisTemplate;

    @GetMapping("/send_code")
    public ResponseResult sendCode(String phone){

        //随机生成6位数值
        String code = RandomStringUtils.randomNumeric(6);
        //发送短信
        sendSmsService.sendMsg(phone,code);
        //把验证码存入redis
        redisTemplate.opsForValue().set(phone,code,60, TimeUnit.SECONDS);

        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);

    }

    @GetMapping("/verify_code")
    public ResponseResult verifyCode(String phone,String code){

        //1.校验验证码是否有效和存在
        String redis_code = redisTemplate.opsForValue().get(phone);

        //2.校验验证码是否正确或过期
        if(!redis_code.equals(code)){
            return ResponseResult.errorResult(AppHttpCodeEnum.DATA_NOT_EXIST,"无效验证码");
        }

        return ResponseResult.errorResult(AppHttpCodeEnum.SUCCESS);

    }

    @PostMapping("/register")
    public ResponseResult register(@RequestBody ApUser apUser) {
        return apUserService.register(apUser);
    }
}
